import React, {
  startTransition,
  Suspense,
  useDeferredValue,
  useState,
} from "react";

const cache = new Map();

function fetchData(id: string) {
  if (!cache.has(id)) {
    cache.set(id, fetchName(id));
  }
  return cache.get(id);
}

function fetchName(id: string) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(id + "的名字");
      console.log("done");
    }, 1000);
  });
}

function UserProfiler(props: { id: string }) {
  const userName = use(fetchData(props.id));
  console.log(userName);
  return <div>{userName}</div>;
}

export function UseProfileRouter() {
  const [id, setId] = useState("");

  const deferedId = useDeferredValue(id);

  function handleChange(event: any) {
    // startTransition(() => {});
    setId(event.target.value);
  }

  return (
    <Suspense fallback="loading">
      <input type="text" value={id} onChange={handleChange} />
      <button>查询</button>
      <UserProfiler id={deferedId}></UserProfiler>
    </Suspense>
  );
}

// This is a workaround for a bug to get the demo running.
// TODO: replace with real implementation when the bug is fixed.
function use(promise: any) {
  if (promise.status === "fulfilled") {
    return promise.value;
  } else if (promise.status === "rejected") {
    throw promise.reason;
  } else if (promise.status === "pending") {
    throw promise;
  } else {
    promise.status = "pending";
    promise.then(
      (result: any) => {
        promise.status = "fulfilled";
        promise.value = result;
      },
      (reason: any) => {
        promise.status = "rejected";
        promise.reason = reason;
      }
    );
    throw promise;
  }
}
